package com.example.nick.bodyapplication.compose

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.SecureFlagPolicy
import androidx.lifecycle.MutableLiveData
import kotlin.math.roundToInt

@ExperimentalAnimationApi
class ComposeActivity : AppCompatActivity() {
    var bglist = mutableListOf<MutableState<Color>>()
    val column = 3
    val row = 2
    var itemW = 0
    var itemH = 0

    var diaLive = MutableLiveData<Boolean>()

    //val viewModel: WeViewModel by viewModels()
    val mkViewModel: MkViewModel by viewModels()

    override fun onBackPressed() {
        if (mkViewModel.currentChat) {
            mkViewModel.currentChat = false
        } else {
            super.onBackPressed()
        }
    }

    @ExperimentalComposeUiApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        diaLive.observe(this, {
//            if (it) {
//                showDialog21()
//            }
//        })
        setContent {
//            MkSettingItem(leftTxt = "left:1", rightSwitch = false, onItemCLick = { flag ->
//                Log.i("Compose", "onItemCLick: $flag")
//            })
            MkDevelopMain(mkViewModel) { onBackPressed() }
//            MkDevelopList { onBackPressed() }
//            PageView(mkViewModel)
//            HelloContent2()
//            ButtonArea(myOnClick = {
//                Toast.makeText(this,"myOnClick，啥都没",Toast.LENGTH_LONG).show()
//            })
//            MyDialog(this)
//            JetpackCompose()
//            AlertDialogDemo(this)
//            ArtistCard2()
            /*val screen_w = resources.displayMetrics.widthPixels
            val screen_h = resources.displayMetrics.heightPixels

//            for (i in 0 until row) {
//                for (j in 0 until column) {
//                    var temp = remember {mutableStateOf(Color.Blue) }
//                    bglist.add(temp)
//                }
//            }
            itemW = screen_w / column
            itemH = screen_h / row

            for (i in 0 until row) {
                for (j in 0 until column) {
                    var temp = remember { mutableStateOf(Color.Blue) }
                    bglist.add(temp)
                }
            }
            motionArea(column, row, screen_w, screen_h)*/
        }
    }

    fun getRC(touchX: Float, touchY: Float): Pair<Int, Int> {
        val c = (touchX / itemW).toInt()
        val r = (touchY / itemH).toInt()
        return Pair(c, r)
    }

    fun getIndex(c: Int, r: Int): Int {
        var c = c
        var r = r
        if (c >= column) {
            c = column - 1
        }
        if (r >= row) {
            r = row - 1
        }
        return r * column + c
    }

    @ExperimentalComposeUiApi
    @Composable
    fun motionArea(column: Int, row: Int, w: Int, h: Int) {
        Log.i("area", "area column:$column, row:$row, w:$w, h:$h")
        val bgArrays = listOf(Color.Blue, Color.Yellow, Color.Red, Color.Cyan)
//    var bgColorArrays = listOf(remember { mutableStateOf(Color.Blue) }, remember { mutableStateOf(Color.Blue) }, remember { mutableStateOf(Color.Blue) }, remember { mutableStateOf(Color.Blue) })
        var curIndex = remember {
            mutableStateOf(0)
        }

        Column(modifier = Modifier.pointerInteropFilter {
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {
                    val (c, r) = getRC(it.x, it.y)
                    val index = getIndex(c, r)
                    curIndex.value = index
                    if (bglist[index].value == Color.Blue || bglist[index].value == Color.Yellow) {
                        bglist[index].value = Color.Red
                    } else if (bglist[index].value == Color.Red) {
                        bglist[index].value = Color.Yellow
                    }
                }
                MotionEvent.ACTION_MOVE -> {
                    val (c, r) = getRC(it.x, it.y)
                    val index = getIndex(c, r)
                    if (curIndex.value != index) {
                        curIndex.value = index
                        if (bglist[index].value == Color.Blue || bglist[index].value == Color.Yellow) {
                            bglist[index].value = Color.Red
                        } else if (bglist[index].value == Color.Red) {
                            bglist[index].value = Color.Yellow
                        }
                    }
                }
            }
            true
        }) {
            for (r in 0 until row) {
                Row(
                    modifier = Modifier
                        .width(w.dp)
                        .height((h / row).dp)
                ) {
                    for (c in 0 until column) {
                        var index = r * column + c
                        Text(
                            "r:$r, c:$c",
                            modifier = Modifier
                                .background(bglist[index].value)
                                .width((w / column).dp)
                                .height((h / row).dp)
//                            .pointerInteropFilter {
//                                when (it.action) {
//                                    MotionEvent.ACTION_DOWN -> {
//                                        curIndex = index
//                                        Log.d("area", "area down r:$r, c:$c, curIndex:$curIndex")
//                                        if (bglist[index].value == Color.Blue || bglist[index].value == Color.Yellow) {
//                                            bglist[index].value = Color.Red
//                                        } else if (bglist[index].value == Color.Red) {
//                                            bglist[index].value = Color.Yellow
//                                        }
//                                    }
//                                    MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
//                                        Log.d("area", "area up r:$r, c:$c")
//                                    }
//                                    MotionEvent.ACTION_MOVE -> {
//                                        Log.d("area", "area move r:$r, c:$c, curIndex:$curIndex, index:$index")
//                                        if (curIndex != index) {
//                                            curIndex = index
//                                            if (bglist[index].value == Color.Blue || bglist[index].value == Color.Yellow) {
//                                                bglist[index].value = Color.Red
//                                            } else if (bglist[index].value == Color.Red) {
//                                                bglist[index].value = Color.Yellow
//                                            }
//                                        }
//                                    }
//                                    else -> false
//                                }
//                                true
//                            }
                        )
                    }
                }
            }
        }
    }

}


//@Preview
@Composable
fun ArtistCard() {
    Column {
        Text("Alfred Sisley", modifier = Modifier.pointerInput(Unit) {
            detectTapGestures(
                onPress = { /* Called when the gesture starts */ },
                onDoubleTap = { /* Called on Double Tap */ },
                onLongPress = { /* Called on Long Press */ },
                onTap = { /* Called on Tap */ }
            )
        })
        Text("3 minutes ago", modifier = Modifier.clickable { })
    }
}

@Composable
fun ArtistCard2() {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Column {
            Text("aaaaa")
        }
        Column {
            Text("name")
            Text("abc")
        }
    }
}

@Composable
fun MyDialog(ctx: Context) {
    Toast.makeText(ctx, "武侠梦醒了，啥都没", Toast.LENGTH_LONG).show()
    val showDia = remember {
        mutableStateOf(true)
    }
    val txtColor = remember {
        mutableStateOf(Color.Black)
    }
    if (showDia.value) {
        Dialog(onDismissRequest = { showDia.value = false }) {
            Column {
                Text(text = "弹了个框", color = txtColor.value)
                Text(
                    text = "hello My",
                    color = Color.Red,
                    fontSize = 40.sp,
                    modifier = Modifier.clickable {
                        if (txtColor.value == Color.Black) {
                            txtColor.value = Color.Red
                        } else {
                            txtColor.value = Color.Black
                        }
                    })
            }
        }
    }
}

@Composable
fun AlertDialogDemo(ctx: Context) {
    val alertDialog = remember { mutableStateOf(false) }
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = {
            alertDialog.value = true
        }) {
            Text(text = "弹了个框")
        }
    }
    showDialog21(ctx, alertDialog)
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun showDialog21(ctx: Context, alertDialog: MutableState<Boolean>) {
    if (alertDialog.value) {
        AlertDialog(
            //当用户尝试通过单击外部或按下后退按钮来关闭对话框时执行。单击关闭按钮时不会调用此方法。
            onDismissRequest = {
                alertDialog.value = false
            },
            //对话框的标题，它应该指定对话框的目的。标题不是强制性的，因为文本中可能有足够的信息。提供的文本样式默认为 Typography.h6
            title = {
                Text(text = "弹了个框")
            },
            //显示有关对话框目的的详细信息的文本。提供的文本样式默认为 Typography.body1
            text = {
                Text(
                    "是否获得屠龙宝刀一把" + "\n" +
                            "是否获得倚天神剑一把"
                )
            },
            //一个按钮，用于确认的操作，从而解决触发对话框的原因。该对话框不会为此按钮设置任何事件，因此它们需要由调用者设置。null则不显示
            confirmButton = {
                TextButton(
                    onClick = {
                        alertDialog.value = false
                        Toast.makeText(ctx, "武侠梦醒了，啥都没", Toast.LENGTH_LONG).show()
                    }
                ) {
                    Text("确认获取", color = Color.Red)
                }
            },
            //用于关闭对话框的按钮。该对话框不会为此按钮设置任何事件，因此它们需要由调用者设置,null则不显示
            dismissButton = {
                TextButton(
                    onClick = {
                        alertDialog.value = false
                    }
                ) {
                    Text("大可不必", color = Color.Red)
                }
            },
            //对话框的背景颜色
            backgroundColor = Color.Blue,
            //此对话框为其子级提供的首选内容颜色。
            contentColor = Color.Red,
            //平台特定的属性，以进一步配置对话框
            properties = DialogProperties(
                //是否可以通过按下后退按钮来关闭对话框。 如果为 true，按下后退按钮将调用 onDismissRequest。
                dismissOnBackPress = true,
                //是否可以通过在对话框边界外单击来关闭对话框。 如果为 true，单击对话框外将调用 onDismissRequest
                dismissOnClickOutside = true,
                //用于在对话框窗口上设置 WindowManager.LayoutParams.FLAG_SECURE 的策略。
                securePolicy = SecureFlagPolicy.Inherit,
                //对话框内容的宽度是否应限制为平台默认值，小于屏幕宽度。
                usePlatformDefaultWidth = true
            )
        )
    }
}